<template>
  <div class="h-full flex-col">
    <SearchForm @handle-reset="resetParams" @handle-search="getList">
      <el-form :model="searchForm" inline>
        <el-form-item>
          <el-input v-model="searchForm.filter_agent_player_name" placeholder="로얄회원ID" />
        </el-form-item>
        <el-form-item>
          <el-input v-model="searchForm.filter_agent_player_id" placeholder="로얄회원번호" />
        </el-form-item>
        <el-form-item>
          <el-input v-model="searchForm.filter_player_id" placeholder="JADE회원번호" />
        </el-form-item>
      </el-form>
    </SearchForm>
    <div class="page-card h-full" v-loading="loading">
      <MyTable :tableData="tableData" :tableColumn="tableColumn" v-slot="sp">
        <el-table :data="tableData" :highlight-current-row="true">
          <el-table-column v-if="sp.ctc.includes('Jade회원번호')" label="Jade회원번호" prop="guid" align="center" />
          <el-table-column v-if="sp.ctc.includes('로얄회원번호')" label="로얄회원번호" align="center">
            <template #default="{ row }">
              <el-tag @click="memberItemAccount(row)">
                <span class="m-cursor-pointer">{{ row.agent_player_id }}</span>
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column v-if="sp.ctc.includes('로얄회원ID')" label="로얄회원ID" prop="agent_player_name" align="center" />
          <el-table-column v-if="sp.ctc.includes('로얄회원등급')" label="로얄회원등급" prop="agent_player_lv" align="center" />
          <el-table-column v-if="sp.ctc.includes('에이전트명')" label="에이전트명" prop="agent_name" align="center" />
          <el-table-column v-if="sp.ctc.includes('브랜드명')" label="브랜드명" prop="agent_brand" align="center" />
          <el-table-column v-if="sp.ctc.includes('리베이트')" label="리베이트" prop="rebate" align="center">
            <template #default="{ row }">
              {{ formatNumber(row.rebate) }}
            </template>
          </el-table-column>
          <el-table-column v-if="sp.ctc.includes('추천인 리베이트')" label="추천인 리베이트" prop="rebate_recommend" align="center">
            <template #default="{ row }">
              {{ formatNumber(row.rebate_recommend) }}
            </template>
          </el-table-column>

          <el-table-column v-if="sp.ctc.includes('기간내입금액')" label="기간내입금액" align="center">
            <template #default="{ row }">
              <el-button @click="memberItemBalance(row)" type="primary" size="small">{{
                row['recharge_btn']
              }}</el-button>
            </template>
          </el-table-column>

          <el-table-column v-if="sp.ctc.includes('가입시간')" label="가입시간" align="center" width="200">
            <template #default="{ row }">
              {{ row.register_ts }}
            </template>
          </el-table-column>
        </el-table>
        <Pagination :pageable="page" :handleSizeChange="handleSizeChange" :handleCurrentChange="handleCurrentChange" />
      </MyTable>

      <el-drawer v-model="memberItemAccountDrawer" :title="memberItemAccountDrawerTitle">
        <div class="m-member-item-account-operation">
          <span>시간선택</span>
          <el-date-picker v-model="dataTimeRange" type="datetimerange" start-placeholder="Start date"
            end-placeholder="End date" format="YYYY-MM-DD HH:mm:ss" date-format="YYYY/MM/DD ddd" time-format="A hh:mm:ss"
            style="margin: 0 10px" />
          <el-button>
            <el-icon @click="memberItemStatHandle">
              <Search />
            </el-icon>
          </el-button>
        </div>
        <div class="m-member-item-account-list">
          <div class="m-member-item-account-item">
            <span class="m-member-item-account-item-title">기간내-총입금:</span>
            <span class="m-member-item-account-item-num">{{
              formatNumber(memberItemAccountDrawerRechargeCnt)
            }}</span>
          </div>
          <div class="m-member-item-account-item">
            <span class="m-member-item-account-item-title">기간내-총출금:</span>
            <span class="m-member-item-account-item-num">{{
              formatNumber(memberItemAccountDrawerWithdrawCnt)
            }}</span>
          </div>
          <div class="m-member-item-account-item">
            <span class="m-member-item-account-item-title">기간내-입출금차액:</span>
            <span class="m-member-item-account-item-num">{{
              formatNumber(memberItemAccountDrawerRechargeCnt - memberItemAccountDrawerWithdrawCnt)
            }}</span>
          </div>
        </div>
      </el-drawer>

      <el-drawer v-model="memberItemBalanceDrawer" :title="memberItemBalanceDrawerTitle">
        <div class="m-member-item-balance-info-wrap">
          <div class="m-member-item-balance-info-item">
            <div class="m-member-item-balance-info-item-item">
              <span>현재잔액:</span>
              <span>{{ memberItemSearchCnt }}</span>
            </div>
            <div class="m-member-item-balance-info-item-item">
              <span>게임선택:</span>
              <span>
                <el-select v-model="memberItemBalanceSearchSelect">
                  <el-option :value="1" label="EVO" />
                  <el-option :value="0" label="PP" />
                </el-select>
              </span>
            </div>
            <div class="m-member-item-btn-wrap">
              <el-button type="primary" @click="memberItemBalanceSearch">잔액조회</el-button>
            </div>
          </div>

          <div class="m-member-item-balance-info-item">
            <div class="m-member-item-balance-info-item-item">
              <span>게임선택:</span>
              <span>
                <el-select v-model="memberItemBalanceModifySelect">
                  <el-option :value="1" label="EVO" />
                  <el-option :value="0" label="PP" />
                </el-select>
              </span>
            </div>
            <div class="m-member-item-balance-info-item-item">
              <span>선택:</span>
              <span>
                <el-radio-group v-model="memberItemBalanceModifyRadio" class="ml-4">
                  <el-radio :label="1" size="large">+</el-radio>
                  <el-radio :label="-1" size="large">-</el-radio>
                </el-radio-group>
              </span>
            </div>
            <div class="m-member-item-balance-info-item-item">
              <span>금액입력:</span>
              <span>
                <el-input v-model="memberItemBalanceModifyInp" placeholder="금액입력" />
              </span>
            </div>
            <div class="m-member-item-btn-wrap">
              <el-button type="primary" @click="memberItemBalanceModifyHandle">머니수정</el-button>
            </div>
          </div>
        </div>
      </el-drawer>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue';
import { useTable } from '@/hooks/useTable';
import {
  playerListApi,
  playerStatApi,
  playerBalanceApi,
  playerBalanceModifyApi
} from '@/api/member/index';
import { formatNumber, formatDate, dataTimeRangeCurTwo, timestampToSeoul } from '@/utils/util';
import { ElMessage } from 'element-plus';
import MyTable from '@/components/MyTable';

const tableColumn = ref([
  'Jade회원번호',
  '로얄회원번호',
  '로얄회원ID',
  '로얄회원등급',
  '에이전트명',
  '브랜드명',
  '리베이트',
  '추천인 리베이트',
  '기간내입금액',
  '가입시간'
]);

const dateTimeRange = dataTimeRangeCurTwo(-6);
const dataTimeRange: any = ref([]);

onMounted(() => {
  dataTimeRange.value = dateTimeRange.map((item) => new Date(item * 1000));
});

const memberItemBalanceDrawer = ref(false);
const memberItemBalanceDrawerTitle = ref('');

const memberItemBalanceSearchSelect = ref(1);
const memberItemBalanceModifySelect = ref(1);
const memberItemBalanceModifyRadio = ref(1);
const memberItemBalanceModifyInp = ref('');
const memberItemBalanceGuid = ref(0);

const memberItemSearchCnt = ref(0);

const memberItemBalance = (row: any) => {
  console.log(row);
  memberItemBalanceDrawer.value = true;
  memberItemBalanceDrawerTitle.value = `닉네임 : ${row.agent_player_name}`;
  memberItemBalanceGuid.value = row.guid;
};

const memberItemBalanceSearch = () => {
  playerBalanceApi({
    guid: memberItemBalanceGuid.value,
    provider: memberItemBalanceSearchSelect.value
  }).then((res: any) => {
    ElMessage({
      type: 'success',
      message: '정상적으로 조회 되였습니다!'
    });
    memberItemSearchCnt.value = res.data.data.balance;
  });
};

const memberItemBalanceModifyHandle = () => {
  const symbole = memberItemBalanceModifyRadio.value;

  playerBalanceModifyApi({
    guid: memberItemBalanceGuid.value,
    provider: memberItemBalanceModifySelect.value,
    amount: memberItemBalanceModifyInp.value * symbole
  }).then((res: any) => {
    if (res.data.status == 0) {
      ElMessage({
        type: 'success',
        message: '성공적으로 수정했습니다!'
      });
    }
  });
};

const memberItemAccountDrawer = ref(false);
const memberItemAccountDrawerTitle = ref('');
const memberItemAccountDrawerPlayerId = ref(0);
const memberItemAccountDrawerRechargeCnt = ref(0);
const memberItemAccountDrawerWithdrawCnt = ref(0);

const memberItemAccount = (row: any) => {
  memberItemAccountDrawer.value = true;
  memberItemAccountDrawerTitle.value = `회원번호: ${row.agent_player_id}`;
  memberItemAccountDrawerPlayerId.value = row.guid;
};

const memberItemStatHandle = () => {
  const params = {
    start_ts: Math.floor(+new Date(dataTimeRange.value[0]) / 1000),
    end_ts: Math.floor(+new Date(dataTimeRange.value[1]) / 1000),
    player_id: memberItemAccountDrawerPlayerId.value
  };
  playerStatApi(params).then((res: any) => {
    const _data = res.data.data;
    memberItemAccountDrawerRechargeCnt.value = _data.recharge;
    memberItemAccountDrawerWithdrawCnt.value = _data.withdraw;
  });
};

const searchForm = reactive({
  filter_agent_player_id: '',
  filter_agent_player_name: '',
  filter_player_id: ''
});

const dataCallBack = (data: any) => {
  const _data = data.data;
  let _list = _data.players.map((item: any) => {
    item.register_ts = timestampToSeoul(item.register_ts * 1000, 'Y-m-d H:i:s', 1);
    item.recharge_btn = '잔액조회 & 수정';
    return item;
  });

  return {
    list: _list,
    total: _data.total_count
  };
};

const { tableData, page, loading, resetParams, getList, handleCurrentChange, handleSizeChange } =
  useTable({
    apiFn: playerListApi,
    params: searchForm,
    callback: dataCallBack
  });
</script>

<style lang="scss" scoped>
.m-member-item-balance-info-wrap {
  display: flex;
}

.m-member-item-balance-info-item:nth-of-type(1) {
  border-right: 1px solid #ddd;
  padding-right: 20px;
}

.m-member-item-balance-info-item:nth-of-type(2) {
  padding-left: 20px;
}

.m-member-item-balance-info-item-item {
  display: flex;
  height: 50px;
  align-items: center;
}

.m-member-item-balance-info-item-item span:nth-of-type(1) {
  width: 100px;
  text-align: right;
  padding-right: 10px;
}

.m-member-item-balance-info-item-item span:nth-of-type(2) {
  flex: 1;
}

.m-member-item-btn-wrap {
  width: 100%;
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.m-member-item-account-operation {
  height: 40px;
  display: flex;
  align-items: center;
}

.m-member-item-account-list {
  margin-top: 20px;
}

.m-member-item-account-item {
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.m-member-item-account-item-title {
  font-size: 14px;
  text-align: right;
  width: 150px;
}

.m-member-item-account-item-num {
  margin-left: 10px;
  width: 200px;
  height: 34px;
  line-height: 34px;
  padding-left: 5px;
  border: 1px solid #ddd;
}
</style>
